package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.LoginEvent;
import com.atguigu.flink.chapter07.util.AtguiguUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/17 15:36
 */
public class Flink05_Project_High_Login {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/LoginLog.csv")
            //            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new LoginEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000L);
            })
            .keyBy(LoginEvent::getUserId)
            .countWindow(2, 1)
            .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                @Override
                public void process(Long key,
                                    Context ctx,
                                    Iterable<LoginEvent> elements,
                                    Collector<String> out) throws Exception {
                    List<LoginEvent> list = AtguiguUtil.toList(elements);
                    if (list.size() == 2) {
                        LoginEvent log1 = list.get(0);
                        LoginEvent log2 = list.get(1);
    
//                        System.out.println(key + " " + (log1.getEventTime() - log2.getEventTime()));
    
                        if (log1.getEventType().equals("fail")
                            && log2.getEventType().equals("fail")
                            && Math.abs(log1.getEventTime() - log2.getEventTime()) <= 2000) {
                            out.collect(key + " 在恶意登录...");
                        }
                    }
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
恶意登录:
    2s内连续两次失败
    
    

 */
